
<script>
import { User,Lock,Picture } from '@element-plus/icons-vue';
import axios from "@/utils/request.js";
import { useAdminStore } from '@/store/admin';
import { adminSelectService } from '@/api/admin';

const adminStore = useAdminStore()
export default {
  name: "Login",
  computed: {
    User() {
      return User
    },
    Lock(){
      return Lock
    },
    Picture(){
      return Picture
    }

  },
  mounted() {
    let image = document.getElementById("imageCode")
    //直接通过访问url的形式生成图形验证码（要加上随机时间，不然浏览器会默认缓存，下次依然还是一样的图片）
    this.axios.get("/account/getCode" + '?timestamp=' + new Date().getTime()).then((res) => {
      console.log(res.data.data.checkCode)
      image.src = res.data.data.checkCode
      this.loginForm.checkCodeKey = res.data.data.checkCodeKey
    })
    // image.src = "/getCode" + '?timestamp=' + new Date().getTime()
  },
  props:['name'],
  data() {
    return {
      //设置图片显示
      isShow1: false,
      isShow2: true,
      // 登录重定向
      redirect:"",
      // 重定向参数
      otherQuery: {},

      // 是否正在登录
      loading: false,
      // 开启大写提示
      capsTooltip: false,
      // 密码控件类型
      passwordType: "password",

      // 登录表单控件
      loginForm:{
        checkCodeKey: "",
        checkCode: "",
        account: "",
        password: "",
      },



      // 控件校验规则
      loginRules: {
        account: [
          {required: true, trigger: "blur", message: '用户名不能为空' },
          {min: 3, max: 15,message: '长度在3到15个字符',trigger: "blur"}
        ],
        password: [
          {required: true, trigger: "blur", message: '密码不能为空'},
          {min: 6, max: 20,message: '长度在6到20个字符',trigger: "blur"}
        ],
      },

    };
  },

  watch: {

    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          // 包含第一个参数的重定向
          this.redirect = query.redirect;
          // 重定向其它的查询参数
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      // 立即执行
      immediate: true,
    },
  },


  methods: {
    login(){
      this.$refs['loginForm'].validate(async (valid) => {
        if(valid) {
          const res = await this.axios.post("/account/login?checkCodeKey="
          + this.loginForm.checkCodeKey + "&checkCode=" + this.loginForm.checkCode +
          "&account=" + this.loginForm.account + "&password=" + this.loginForm.password)
          if(res.data.status === 'success'){//表单校验合法
            //根据userId查询管理员信息
            const res1 = await adminSelectService(this.loginForm.account)
            console.log(res1.data)
            if(res1.data.status === 'success'){
              //将管理员信息存储在Pinia中
              const { userId,userName,role } = res1.data.data.list[0]
              await adminStore.setAdmin({userId,userName,role})
            }
            setTimeout(() => {
              this.$router.push("/home")
            },300)
            this.$message.success("登录成功")
          }else{
            this.$message.error(res.data.info)
            this.refrushCode()
          }

        }
      });
    },
    //刷新验证码
    refrushCode(){
      const image = document.getElementById("imageCode")
      this.axios.get("/account/getCode" + '?timestamp=' + new Date().getTime()).then((res) => {
        image.src = res.data.data.checkCode
        this.loginForm.checkCodeKey = res.data.data.checkCodeKey
      })

      // image.src = "/getCode" + '?timestamp=' + new Date().getTime()
    },


    // 获取查询参数
    getOtherQuery(query) {
      return Object.keys(query).reduce((obj, value) => {
        // 排除重定向和第一个查询能数
        if (value !== "redirect") {
          obj[value] = query[value];
        };
        return obj;
      },{});
    },

  },

};
</script>

<template>
  <div class="login-box">
    <div class="login-body">
      <div class="login-right" style="position: absolute; width: 20%; margin-left: 760px;
            margin-top: 10%;
">
        <h4 class="login-title" style="margin-bottom: 5%">
          Acm管理系统<br>登录
        </h4>
        <el-form
          ref="loginForm"
          autocomplete="on"
          :model="loginForm"
          :rules="loginRules"
          label-position="left">

          <el-form-item prop="account" style="margin-bottom:10%;">
            <el-input
              style="line-height: 50px"
              type="text"
              tabindex="1"
              ref="account"
              name="account"
              autocomplete="on"
              :prefix-icon="User"
              placeholder="请输入账户名称"
              v-model="loginForm.account"
            />
          </el-form-item>

          <el-form-item prop="password" style="margin-bottom:10%;">
            <el-tooltip>
              <el-input
                tabindex="2"
                show-password
                ref="password"
                name="password"
                autocomplete="on"

                :key="passwordType"
                :type="passwordType"

                placeholder="请输入密码"
                :prefix-icon="Lock"
                @keyup.enter.native="login"

                @blur="capsTooltip = false"
                v-model="loginForm.password"/>

            </el-tooltip>

          </el-form-item>

          <div style="display: flex;align-items: center;justify-content: center;">
            <el-input
              tabindex="2"
              ref="imageCode"
              name="imageCode"
              autocomplete="on"
              style="width: 60%;left: -15px;"

              placeholder="请输入验证码"
              :prefix-icon="Picture"
              @keyup.enter.native="login"

              v-model="loginForm.checkCode"/>

            <img id="imageCode" alt="图形验证码" @click="refrushCode" style="width: 30%;cursor: pointer">
          </div>

          <el-button
            type="primary"
            :loading="loading"
            @click="login"
            style="font-family: 楷体;font-size: 20px;margin-left: 80px;margin-top: 5vh;width: 150px"
          >
            <i class="el-icon-s-promotion"/> 登 录
          </el-button>

        </el-form>
      </div>

    </div>


  </div>
</template>

<style>


.login-box{
  position: absolute;
  background-image: url(../assets/image/loginBackground.jpg);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 100%;
  height: 100%;
  display: flex;

  .el-input__inner{
    height: 40px;
    font-size: 16px;
  }
}
.login-title{

  font-family: 楷体;

  text-align: center;
  color: #fae2b7;
  font-size: 24px;
  font-weight: 700;
  line-height: 40px;
  letter-spacing: 5px;
}
.login-left-bottom{
  color: indigo;
  font-size: x-large;
  font-style: initial;
  position: absolute;
  width: 45%;
  height: 63%;
  margin-left: 280px;
  margin-top: 100px;
  background-size: 1000px;
  background-position-x: -280px;

}

.login-body{
  width: 100%;
  display: flex;
  height: 100%;
}
.login-right{
  position: relative;
  left: -180px;
  border-radius: 10px 10px 10px 10px;
  height: 400px;
  margin: auto auto;
  background-color: rgba(0,0,0,.5);
  padding: 10px 35px;
}

/* 使用@keyframes定义动画 */
@keyframes colorChange {
  0% {
    color: darkseagreen; /* 动画开始时的颜色 */
  }
  50% {
    color: orange; /* 动画中间时的颜色 */
  }
  100% {
    color: gray; /* 动画结束时的颜色 */
  }
}

@media screen and (max-device-width: 600px) {
  .login-left{
    display: none !important;
  }
  .login-right{
    border-radius:10px !important;
  }

}

</style>
